<?php
class Sabai_Model_Schema
{
    var $_db;

    function setDB(&$db)
    {
        $this->_db =& $db;
    }

    /**
     * Gets the name of foreign tables
     *
     * @return array
     */
    function getForeignSchemaNames()
    {
        return array();
    }

    function create()
    {
        switch (strtolower($this->_db->getScheme())) {
            case 'sqlite':
                return $this->_create($this->_getSQLiteSchema());
            case 'postgresql':
                return $this->_create($this->_getPostgreSQLSchema());
            case 'mysql':
                return $this->_create($this->_getMySQLSchema());
            default:
                trigger_error(sprintf('Unknown database scheme %s', $this->_db->getScheme()), E_USER_WARNING);
                return false;
        }
    }

    function _create($tables)
    {
        $tables_created = array();
        foreach (array_keys($tables) as $table_name) {
            if (!$this->_db->tableExists($table_name)) {
                $tables_created[] = $table_name;
                foreach ($tables[$table_name] as $sql) {
                    if (!$this->_db->exec($sql, false)) {
                        trigger_error(sprintf('Failed create table %s', $table_name), E_USER_WARNING);
                        foreach ($tables_created as $table) {
                            if ($this->_db->tableExists($table)) {
                                if (!$this->_db->dropTable($table)) {
                                    trigger_error(sprintf('Failed drop table %s', $table_name), E_USER_WARNING);
                                }
                            }
                        }
                        return false;
                    }
                }
            }
        }
        return true;
    }

    function drop()
    {
        switch (strtolower($this->_db->getScheme())) {
            case 'sqlite':
                return $this->_drop($this->_getSQLiteSchema());
            case 'postgresql':
                return $this->_drop($this->_getPostgreSQLSchema());
            case 'mysql':
                return $this->_drop($this->_getMySQLSchema());
            default:
                trigger_error(sprintf('Unknown database scheme %s', $this->_db->getScheme()), E_USER_WARNING);
                return false;
        }
    }

    function _drop($tables)
    {
        foreach (array_keys($tables) as $table_name) {
            //if ($this->_db->tableExists($table_name)) {
                $this->_db->dropTable($table_name);
            //}
        }
        return true;
    }

    function _getMySQLSchema(){}
    function _getPostgreSQLSchema(){}
    function _getSQLiteSchema(){}
}